//
//  ZJEventKit.m
//  添加事件到系统日历
//
//  Created by zhengju on 2017/3/18.
//  Copyright © 2017年 zhengju. All rights reserved.
//

#import "ZJEventKit.h"

#import "ZJEKEvent.h"

#import <EventKit/EventKit.h>

@interface ZJEventKit()
@property(nonatomic,strong)EKEventStore *eventStore;

@property(nonatomic,strong)NSMutableArray *events;
@end

@implementation ZJEventKit
-(NSMutableArray *)events{
    if (_events == nil) {
        _events = [NSMutableArray arrayWithCapacity:0];
    }
    return _events;
}
static ZJEventKit * eventKit;

+ (instancetype)eventKit {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        eventKit = [[self alloc]init];
        //事件市场
        eventKit.eventStore = [[EKEventStore alloc] init];
    });
    return eventKit;
}
- (ZJEKEvent *)zjEKEvent{

    return (ZJEKEvent *)[ZJEKEvent eventWithEventStore:self.eventStore];
}
- (void)startZJEventKitWithdelegate:(id<ZJEventKitDelegate>) delegate{
    self.delegate = delegate;
  
   // NSPredicate * predicate = [self.eventStore predicateForRemindersInCalendars:@[[self.eventStore defaultCalendarForNewEvents]]];
   // NSPredicate *predicate = [self.eventStore predicateForRemindersInCalendars:nil];
//    [self.eventStore fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders) {
//        
//        for (EKReminder *reminder in reminders) {
//            
//            // do something for each reminder
//            
//        }
//        
//    }];
   
    
    NSArray *tempA  =[self.eventStore calendarsForEntityType:EKEntityTypeEvent];
    
    //6.0及以上通过下面方式写入事件
    if ([self.eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
        {
        // the selector is available, so we must be on iOS 6 or newer
        [self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error)
                    {
                    //错误细心
                    // display error message here
                    }
                else if (!granted)
                    {
                    //被用户拒绝，不允许访问日历
                    if (self.delegate && [self.delegate respondsToSelector:@selector(ZJEventKitAddEventErrorUserCancel)]) {
                        [self.delegate ZJEventKitAddEventErrorUserCancel];
                    }
                    }
                else
                    {
                    // access granted
                    // ***** do the important stuff here *****
                    
                    
                    }
            });
        }];
        }
    else
        {
        // this code runs in iOS 4 or iOS 5
        // ***** do the important stuff here *****
        
        
        }
}
-(void)addEvent:(ZJEKEvent *)event{
    //事件保存到日历
    if ([self.eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
        {

    event.location = @"我在杭州西湖区留和路";
        
    NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
    [tempFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];

    event.allDay = YES;
    
    //添加提醒
    [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -60.0f * 24]];
    [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -15.0f]];
    
    [event setCalendar:[self.eventStore defaultCalendarForNewEvents]];
    NSError *err;
    [self.eventStore saveEvent:event span:EKSpanThisEvent error:&err];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(ZJEventKitAddEventSuccess)]) {
        [self.delegate ZJEventKitAddEventSuccess];
    }
        }else{
            //4.0和5.0通过下述方式添加
            
            //保存日历
            EKEvent *event  = [EKEvent eventWithEventStore:self.eventStore];
            event.title     = @"哈哈哈，我是日历事件啊";
            event.location = @"我在杭州西湖区留和路";
            
            NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
            [tempFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
            
            event.startDate = [[NSDate alloc]init ];
            event.endDate   = [[NSDate alloc]init ];
            event.allDay = YES;
            
            
            [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -60.0f * 24]];
            [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -15.0f]];
            
            [event setCalendar:[self.eventStore defaultCalendarForNewEvents]];
            NSError *err;
            [self.eventStore saveEvent:event span:EKSpanThisEvent error:&err];
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(ZJEventKitAddEventSuccess)]) {
                [self.delegate ZJEventKitAddEventSuccess];
            }

        }
}
-(void)eventsWithStartDate:(NSDate *)startDate endDate:(NSDate *)endDate{
    NSPredicate * predicate =  [self.eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:@[[self.eventStore defaultCalendarForNewEvents]]];
    self.events = [NSMutableArray arrayWithArray:[self.eventStore eventsMatchingPredicate:predicate]];
    NSLog(@"events---%@",self.events);
    NSLog(@"events.count---%lu",(unsigned long)self.events.count);
 
    NSArray * newEvents =  [self.events sortedArrayUsingSelector:@selector(compareStartDateWithEvent:)];
    [self.events removeAllObjects];
    [self.events addObjectsFromArray:newEvents];
}
-(void)deleteEvent{
    if (self.events.count == 0) {
        NSLog(@"请先查找事件---");
        return;
    }
    EKEvent * event = [self.events lastObject];
    NSError *err;
 
    BOOL remove =  [self.eventStore removeEvent:event span:EKSpanThisEvent error:&err];
    if (remove) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(ZJEventKitAddEventErrorUserDeleteSuccess)]) {
            [self.delegate ZJEventKitAddEventErrorUserDeleteSuccess];
        }

    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(ZJEventKitAddEventErrorUserDeleteFailure)]) {
            [self.delegate ZJEventKitAddEventErrorUserDeleteFailure];
        }
    }
}
-(void)editEvent{
    if (self.events.count == 0) {
        NSLog(@"请先查找事件---");
        return;
    }
    EKEvent * event = self.events[0];
    NSError *err;
    event.title = @"这是修改后的事件";
  BOOL edit =  [self.eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
    if (edit) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(ZJEventKitAddEventErrorEditSuccess)]) {
            [self.delegate ZJEventKitAddEventErrorEditSuccess];
        }
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(ZJEventKitAddEventErrorEditFailure)]) {
            [self.delegate ZJEventKitAddEventErrorEditFailure];
        }
    }
}
@end
